/**
 * @author Alex Tan 2015-12-25
 * <p>
 * Spring mvc Controller class for Equipment
 */

package com.jhws.business.device.controller;

import com.alibaba.fastjson.JSON;
import com.jhws.business.device.bo.LogDevUnlock;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.business.device.bo.DevInfo;
import com.jhws.business.device.service.LogDevUnlockService;
import com.jhws.business.local.service.LocalService;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.device.bo.DeviceConstant;
import com.jhws.business.device.bo.DeviceFaceRegisterdBo;
import com.jhws.business.device.service.DeviceService;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.common.base.bo.Global;
import com.jhws.core.log.bo.LogConstants;
import com.jhws.core.log.service.ILogService;
import com.jhws.core.push.PushXinGe;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.util.AccountsUtils;
import com.jhws.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Controller
@RequestMapping({"/EquCtrl", "/dev"})
public class EquCtrl {
    @Resource
    ITblCommDimService ICommService;
    @Resource
    private RedisTemplate stringTemplate;
    @Resource
    private ILogService ILogService;
    @Resource
    private ITblOwnerDimService IOwnerService;
    @Resource
    private LocalService localService;
    @Resource
    private LogDevUnlockService logDevUnlockService;
    @Resource
    private DeviceService deviceService;

    @RequestMapping("manage.x")
    public String AddEqus(HttpServletRequest request, String currComm) throws Exception {
        List<TblCommDimBo> list = ICommService.findTblCommDimByWhere("1=1");
        request.setAttribute("commList", list);
        return "business/equDim/addTblEquDim";
    }

    @RequestMapping("list.x")
    public ModelAndView ListEquInfo(HttpServletRequest request) throws Exception {
        ModelAndView mv = new ModelAndView();
        List<TblCommDimBo> commDimBoList = ICommService.findCommList(null);
        if (commDimBoList.size() != 0) {
            if (!SecurityUtils.getSubject().hasRole(Global.ROLE_PROPERTY_ADMIN)) {
                request.setAttribute("commDimList", commDimBoList);
            } else {
                request.setAttribute("commDimBo", commDimBoList.get(0));
            }
        }
        mv.setViewName("business/equDim/devicesList");
        return mv;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("queryEquList.x")
    @ResponseBody
    public Object queryEquList(@RequestParam Map param) throws Exception {
        Map<String, String> devInfoMap = null;
        List<DevInfo> devInfos = new ArrayList<>();
        Map<String, Object> result = new HashMap<>();
        String buildingInfo = "";
        String commCode = MapUtils.getString(param, "commCode", "");
        if (StringUtils.isEmpty(commCode)) {
            return new JsonRespData("", -1, "必须携带小区编号");
        }

        int page = MapUtils.getIntValue(param, "page");
        int pageSize = MapUtils.getIntValue(param, "pageSize");

        String buildingCode = MapUtils.getString(param, "buildingCode", "");
        String unitCode = MapUtils.getString(param, "unitCode", "");
        String floorCode = MapUtils.getString(param, "floorCode", "");
        String roomCode = MapUtils.getString(param, "roomCode", "");
        String type = MapUtils.getString(param, "type", "");
        String state = MapUtils.getString(param, "state", "");

        TblCommDimBo commDimBo = ICommService.findTblCommDimByCommCode(commCode);
        devInfoMap = deviceService.getDeviceListByComm(commCode);
        TreeMap<String, String> treeMap = new TreeMap(devInfoMap);
        buildingInfo += commCode;

        if (!StringUtils.isEmpty(buildingCode))
            buildingInfo += buildingCode;
        else
            buildingInfo += "[0-9][0-9]";

        if (!StringUtils.isEmpty(unitCode))
            buildingInfo += unitCode;
        else
            buildingInfo += "[0-9][1-9]";

        if (StringUtils.isEmpty(type) && StringUtils.isEmpty(buildingCode) && StringUtils.isEmpty(unitCode))
            buildingInfo = ".*";
        else if (StringUtils.isEmpty(type))
            buildingInfo += ".*";
        else if (Integer.valueOf(type) == DeviceConstant.MANAGE_TYPE)
            buildingInfo = commCode + "0000000[1-9]";
        else if (Integer.valueOf(type) == DeviceConstant.OUTDOOR_TYPE)
            buildingInfo += "000[1-9]";
        else if (Integer.valueOf(type) == DeviceConstant.WALL_TYPE)
            buildingInfo += "000[a-z]";
        else if (Integer.valueOf(type) == DeviceConstant.VOICE_GATEWAY_TYPE)
            buildingInfo = commCode + "_PstnServer";
        else {
            if (!StringUtils.isEmpty(floorCode))
                buildingInfo += floorCode;
            else
                buildingInfo += "[0-9][1-9]";

            if (!StringUtils.isEmpty(roomCode))
                buildingInfo += roomCode;
            else
                buildingInfo += "[0-9][1-9]";
        }

        /* 先过滤所有的 */
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            String[] values = value.split(",");
            if (key.matches(buildingInfo)) {
                if (values.length > 1 && StringUtils.isNotEmpty(state) && !state.equals(values[2]))
                    continue;
                DevInfo devInfo = new DevInfo();
                devInfo.setCommCode(commCode);
                devInfo.setCommName(commDimBo.getCommName());
                devInfo.setDeviceNum(key);
                devInfo.setVersionNumber(values[0]);
                if (values.length > 1) {
                    devInfo.setTime(values[1]);
                    devInfo.setStatus(values[2]);
                }
                devInfos.add(devInfo);
            }
        }

        int size = devInfos.size();
        int start = (page - 1) * pageSize;
        int end = (start + pageSize) > size ? size : (start + pageSize);
        if (start > end)
            start = end - pageSize > 0 ? end - pageSize : 0;
        List<DevInfo> list = devInfos.subList(start, end);
        List retList = deviceService.getCommDevices(commDimBo, list);

        if (size > 0) {
            List<DeviceFaceRegisterdBo> deviceFaceRegisterds = deviceService.getDevFaceRegisteredByWhere("where comm_code = '" + commCode + "'");
            if (deviceFaceRegisterds != null) {
                for (DevInfo devInfo : list) {
                    for (DeviceFaceRegisterdBo deviceFaceRegisterd : deviceFaceRegisterds) {
                        if (devInfo.getDeviceNum().equals(deviceFaceRegisterd.getDevNumber())) {
                            devInfo.setFacePerm(true);
                            break;
                        }
                    }
                }
            }
        }
        result.put("list", retList);
        result.put("size", size);
        result.put("ret_code", 1);
        return new JsonRespData("", 1, result);
    }

    @RequestMapping("updateApp.x")
    @ResponseBody
    public JsonRespData updateApp(String devicesNum) {
        PushXinGe.androidPushSingleAccount(devicesNum, "UPDATE_APP", JSON.toJSONString(new JsonRespData("UPDATE_APP", 1, "update_app")));
        return new JsonRespData("updateApp", 1, "成功");
    }


    /**
     * 在设备信息列表中删除离线的设备数据
     * 会从redis缓存中删除
     *
     * @param deviceNum 梯口机设备编号
     * @return
     */
    @RequestMapping("deleteDevice.x")
    @ResponseBody
    public JsonRespData deleteDevice(String deviceNum) {
        HashOperations<String, String, String> hashOperations = stringTemplate.opsForHash();
        hashOperations.delete("online:comm:" + AccountsUtils.getCommCode(deviceNum), deviceNum);
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("getDevUnlockLog.x")
    @ResponseBody
    public JsonRespData getDevUnlockLog(String commCode, String timeStart, String timeEnd, String type, String building, String unit, String ownerName, String ownerMob) throws Exception {
        if (localService.isLanMode()) {
            return new JsonRespData("", 1, logDevUnlockService.findFeedbackListPage(commCode, timeStart, timeEnd, type, building, unit, ownerName, ownerMob));
        }

        String query = "* ";
        if (StringUtils.isNotEmpty(type))
            query += " and message.type = '" + type + "'";
        if (StringUtils.isNotEmpty(building)) {
            query += " and message.building = '" + building + "'";
        }
        if (StringUtils.isNotEmpty(unit)) {
            query += " and message.unit = '" + unit + "'";
        }
        if (StringUtils.isNotEmpty(commCode))
            query += " and message.commCode = '" + commCode + "'";

        String where = "";
        if (StringUtils.isNotEmpty(ownerName))
            where += "where comm_code = '" + commCode + "'  and owner_name = '" + ownerName + "' ";

        if (StringUtils.isNotEmpty(ownerMob))
            where += "where comm_code = '" + commCode + "'  and owner_mob = '" + ownerMob + "'";

        if (StringUtils.isNotEmpty(where)) {
            List<TblOwnerDimBo> ownerDimBos = IOwnerService.findTblOwnerDimByWhere(where);
            if (ownerDimBos != null && ownerDimBos.size() != 0) {
                query += " and (";
                for (TblOwnerDimBo owner : ownerDimBos) {
                    query += " message.ownerCode = '" + owner.getOwnerCode() + "' or";
                }
                query += " NULL)";
            }
        }
        Integer iTimeStart = null;
        if (StringUtils.isNotEmpty(timeStart)) {
            iTimeStart = Math.toIntExact(DateUtil.convert2long(timeStart, DateUtil.DATE_FORMAT) / 1000);
        }
        Integer iTimeEnd = null;
        if (StringUtils.isNotEmpty(timeStart)) {
            iTimeEnd = Math.toIntExact(DateUtil.convert2long(timeEnd, DateUtil.DATE_FORMAT) / 1000);
        }
        Map map = ILogService.queryPage(LogConstants.recordsLogStore, LogConstants.topicUnlock, iTimeStart, iTimeEnd, query, LogDevUnlock.class);
        List<LogDevUnlock> data = (List) map.get("list");
        for (LogDevUnlock logDevUnlock : data) {
            if (StringUtils.isNotEmpty(logDevUnlock.getOwnerCode())) {
                TblOwnerDimBo owner = IOwnerService.findTblOwnerDimById(logDevUnlock.getOwnerCode());
                if (owner != null) {
                    logDevUnlock.setRoomInfo(owner.getRoomInfo());
                    logDevUnlock.setOwnerName(owner.getOwnerName());
                }
            } else if (StringUtils.isNotEmpty(logDevUnlock.getOwnerMob()) && StringUtils.isNotEmpty(logDevUnlock.getRoomInfoNum())) {
                List<TblOwnerDimBo> ownerList = IOwnerService.findTblOwnerDimByWhere("where owner_mob = '" + logDevUnlock.getOwnerMob() + "' and room_info_num = '" + logDevUnlock.getRoomInfoNum() + "'");
                if (ownerList != null && ownerList.size() != 0) {
                    logDevUnlock.setRoomInfo(ownerList.get(0).getRoomInfo());
                    logDevUnlock.setOwnerName(ownerList.get(0).getOwnerName());
                }
            }
        }

        return new JsonRespData("", 1, map);
    }

    /**
     * 开关人脸权限
     *
     * @param state
     * @param devNumber
     * @return
     * @throws Exception
     */
    @RequestMapping({"switchFacePerm.x"})
    @ResponseBody
    JsonRespData switchFacePerm(Integer state, String devNumber) throws Exception {
        String ret = deviceService.updateFacePerms(state, devNumber, "true");
        if (ret != null)
            return new JsonRespData("", -1, ret);
        return new JsonRespData("", 1, "操作成功");
    }
}
